//created by: JIAN HUA
Ext.define('MajorProjectSenchaTouch.controller.NewArrivals', {
     extend: 'Ext.app.Controller',
     config:{
         views: ['NewArrivals.NewArrivals','NewArrivals.NewArrivalsSelectType', 'NewArrivals.NewArrivalsList','NewArrivals.NewArrivalsSort', 'SearchModule.DisplayResult'],
        refs:{
             navView: 'mainNavView',
           
             newarrivalspage: 'newarrivalspage',
			
            selectedfield: '#selecttypeField',
			sorterfield:'#newsorterField',
            resultListPage: 'newArrivalList',
            searchResultPage: 'newarrivalspage',
		
            resultRangeButton: '#resultrangeBtn',
			searchButton:'#resultsummaryBtn',
			basecon: '#basecon',
			prevNewArrivalBtn: 'button[action=getprevNewArrivalsResult]',
			nextNewArrivalBtn: 'button[action=getnextNewArrivalsResult]',
			nextResultsBtn: '#naviBtnNCusArrivals',
            prevResultsBtn: '#naviBtnPCusArrivals',
		
        },
		control:
		{
			nextNewArrivalBtn:{
                tap: 'getnextNewArrivalsResult'
            },
            prevNewArrivalBtn:{
                tap: 'getprevNewArrivalsResult'
            },
			searchResultPage:{
				resetFilter: 'setToDefault',
				loadNewArrivals : 'loadNewArrStore'
			},
		}
    },
	
	goSelectedType: function()
	{
		 var selectedfield = this.getSelectedfield().getValue();
		
		  var searchBtn = this.getSearchButton();
            searchBtn.setDisabled(true);
          
       
            //set the condition to be pass to load store
            var basicfiltervalue = selectedfield + 'U5R' ;
            this.loadNewArrStore(basicfiltervalue);
	},
	
	loadNewArrStore: function(bkw)
    {   
        var con = this.getNewarrivalspage();
        con.setMasked({
            xtype: 'loadmask',
            message: 'Please wait...'
        });
        var scope = this;
        //get store
        var resultInfoStore = Ext.getStore('ResultsInfo');
        var resultStore = Ext.getStore('Results');
        
        //empty the store first
        resultInfoStore.removeAll();
        resultStore.removeAll();
        
        var searchBtn = scope.getSearchButton();
        
        //load the store
        resultInfoStore.load({
            callback: function(records, operation, success) {
                // the operation object contains all of the details of the load operation                        
                var setnumber = '';
                var numentries = '';
                var numrecords = '';
                resultInfoStore.each(function(record){
                    setnumber = record.get('setnumber');
                    numentries = record.get('numentries');
                    numrecords = record.get('numrecords');
                });
                
                    //get the result range (start)
                    var nextstartresultvar = resultInfoStore.getAt(0).get('currentstart');
                    //get the result range (end)
                    var nextendresultvar = resultInfoStore.getAt(0).get('currentend');
                    //get the number of entries
                    var getmaxnumberrecord = resultInfoStore.getAt(0).get('numentries');
                    //get the search keyword
                    var searchkw = resultInfoStore.getAt(0).get('keyword');
                  
                    var newset = '';
                    if(getmaxnumberrecord <10){
                        //set search condition (setnumber, page (1), sortby(year), numberofrecordstoretrieve(getmaxnumberrecord)) [split by U5R]
                        newset = setnumber + 'U5R1' + 'U5RYearU5R' + getmaxnumberrecord;
                    }
                    else{
                        //set search condition (setnumber, page (1), sortby(year), numberofrecordstoretrieve(10)) [split by U5R]
                        newset = setnumber + 'U5R1' + 'U5RYearU5R10';
                    }
                
                    if(setnumber == ""){
                    //do nothing
                    }
                    else{
                        resultStore.load({
                            url: MajorProjectSenchaTouch.app.serverUrl +'results/retrieveList/' + newset //retrieveList
                        }); 
                    }
                    //hide the loading mask
                    con.setMasked(false);
                   
                    
                    //get the prev page button
                    var prevPageBtn = scope.getPrevResultsBtn();
                    
                    //set and display (result range)
                    var displaytext = 'Result ' + nextstartresultvar + ' - ' + nextendresultvar + ' of ' + getmaxnumberrecord;
                    var resultRangeBtn = scope.getResultRangeButton();
                    resultRangeBtn.setHtml(displaytext);
          
                    //disable the prev page button if the start result range is 1
                    if(nextstartresultvar == 1){
                        prevPageBtn.setDisabled(true);
                    }
                    else{
                        prevPageBtn.setDisabled(false);
                    }
                    
                    //set and display (results found for keyword)
                    var pushtext = 'We found ' + numrecords + ' items(s) matching your search for ' + searchkw;
                    var resultSummaryBtn = scope.getSearchButton();
                   
                    
                    searchBtn.setDisabled(false);
               // }
            },//callback
            url: MajorProjectSenchaTouch.app.serverUrl +'NewArrivals/newAList/'+ bkw
        });
    },

    getnextNewArrivalsResult: function(){
        var scope = this;
        //disable next page button
        var nextPageBtn = this.getNextResultsBtn();
        nextPageBtn.setDisabled(true);
        
        //get the prev page button and set it enabled
        var prevPageBtn = scope.getPrevResultsBtn();
        prevPageBtn.setDisabled(false);
                    
        //get store
        var store = Ext.getStore('ResultsInfo');     
        
        //get the result range (start)
        var nextstartresultvar = store.getAt(0).get('currentstart');
        
        //get the result range (end)
        var nextendresultvar = store.getAt(0).get('currentend');
        
        //get number of entries
        var setnumber = store.getAt(0).get('setnumber');
        
        //get number of entries
        var getmaxnumberrecord = store.getAt(0).get('numentries');
        
        //check if next result range is more then the number of entries
        var checkresult = getmaxnumberrecord - nextendresultvar;
        
        //display message if no more results to show
        if(checkresult == 0){
            Ext.Msg.alert(MajorProjectSenchaTouch.app.noMoreResultTitle,MajorProjectSenchaTouch.app.noMoreResultBody);
            nextPageBtn.setDisabled(false);
        }else{
            //set new start range
            var nextstartresult = nextendresultvar + 1;
            //set new end range
            var nextendresult = nextendresultvar + 10;
        
            //reload result list dataview
            var resultStore = Ext.getStore('Results');
            resultStore.removeAll();        
            var resultList = this.getResultListPage();
            resultList.destroy();
            var searchResultPage = this.getSearchResultPage();
            resultList = Ext.create('MajorProjectSenchaTouch.view.NewArrivals.NewArrivalsList');
            searchResultPage.add(resultList);
            
            var newset = '';
            if(checkresult < 10){
                //set search condition (setnumber, page (nextstartresult), sortby(year), numberofrecordstoretrieve(checkresult)) [split by U5R]
                newset = setnumber + 'U5R' + nextstartresult + 'U5RYearU5R' + checkresult;
                nextendresult = nextendresultvar + checkresult;
            }
            else{
                //set search condition (setnumber, page (nextstartresult), sortby(year), numberofrecordstoretrieve(10)) [split by U5R]
                newset = setnumber + 'U5R' + nextstartresult + 'U5RYearU5R10';
            }
           
            //load next page
            resultStore.load({
                callback: function(records, operation, success) {
                    //get the current page number
                    var getcurrentpagenum = store.getAt(0).get('currentpagenumber');
                    var nextpagenumber = getcurrentpagenum + 1;
                    
                    //set currentstart in store to nextstartresult
                    store.getAt(0).set('currentstart', nextstartresult);
                    //set currentend in store to nextendresult
                    store.getAt(0).set('currentend', nextendresult);
                    //set currentpagenumber in store to nextpagenumber
                    store.getAt(0).set('currentpagenumber', nextpagenumber);
                    
                    //display the record range
                    var displaytext = 'Result ' + nextstartresult + ' - ' + nextendresult + ' of ' + getmaxnumberrecord;
                    var resultRangeBtn = scope.getResultRangeButton();
                    resultRangeBtn.setHtml(displaytext);
                    //enable next page button
                    nextPageBtn.setDisabled(false);
                },//callback
                url: MajorProjectSenchaTouch.app.serverUrl +'NewArrivals/retrieveSortList/' + newset
            });
        }
    },
	
	getprevNewArrivalsResult: function(){
        var scope = this;
        var store = Ext.getStore('ResultsInfo');
        var newset = '';
        
        //disable prev page button
        var prevPageBtn = this.getPrevResultsBtn();
        prevPageBtn.setDisabled(true);
       
        //get the setnumbers and numbers of entries from the resultInfo store
        var setnumber = '';
        var numentries = '';
        store.each(function(record){
            setnumber = record.get('setnumber');
            numentries = record.get('numentries');
        });
       
        //get the result range (start)
        var prevstartresultvar = store.getAt(0).get('currentstart');
        var prevstartresult = prevstartresultvar - 10;
        
        //get the result range (end)
        var prevendresultvar = store.getAt(0).get('currentend');
        var prevendresult = prevendresultvar - 10;
        
        //get currentpage number
        var getcurrentpagenum = store.getAt(0).get('currentpagenumber');        
        
        if(getcurrentpagenum == 1){
        }
        else{
            //reload result list dataview
            var resultStore = Ext.getStore('Results');
            resultStore.removeAll();        
            var resultList = this.getResultListPage();
            resultList.destroy();
            var searchResultPage = this.getSearchResultPage();
            resultList = Ext.create('MajorProjectSenchaTouch.view.NewArrivals.NewArrivalsList');
            searchResultPage.add(resultList);
        
            //get the number of records that is being displayed
            var resultdisplaycount = prevendresultvar - prevstartresultvar;
            var resultdisplaycountAdd = resultdisplaycount + 1;
            if(resultdisplaycount < 9){
                prevstartresult = prevstartresultvar - 10;
                newset = setnumber + 'U5R' + prevstartresult + 'U5RnaU5R10';
                prevendresult = prevendresultvar- resultdisplaycountAdd;
            }
            else{
                newset = setnumber + 'U5R' + prevstartresult + 'U5RnaU5R10';
            }
            //load prev page
            resultStore.load({
                callback: function(records, operation, success) {
                    var prevpagenumber = getcurrentpagenum - 1;
                    store.getAt(0).set('currentstart', prevstartresult);
                    store.getAt(0).set('currentend', prevendresult);
                    store.getAt(0).set('currentpagenumber', prevpagenumber);
         
                    //display page range
                    var displaytext = 'Result ' + prevstartresult + ' - ' + prevendresult + ' of ' + numentries;
                    var resultRangeBtn = scope.getResultRangeButton();
                    resultRangeBtn.setHtml(displaytext);
                    //disable prev page button if it's already at the first result
                    if(prevstartresult == 1){
                        prevPageBtn.setDisabled(true);
                    }
                    else{
                        prevPageBtn.setDisabled(false);
                    }
                },//callback
                url: MajorProjectSenchaTouch.app.serverUrl + 'NewArrivals/retrieveSortList/' + newset
            });
        }
    },
	
	goSortResult: function(){
        var scope = this;
        var sortfield = this.getSorterfield();
        var sortkey = sortfield.getValue();
        //load the stores
        var store = Ext.getStore('ResultsInfo');     
        var resultStore = Ext.getStore('Results');
                
        //reload result list dataview
        resultStore.removeAll();        
        var resultList = this.getResultListPage();
        resultList.destroy();
        var searchResultPage = this.getSearchResultPage();
        resultList = Ext.create('MajorProjectSenchaTouch.view.NewArrivals.NewArrivalsList');
        searchResultPage.add(resultList);
            
        //get the current set of result setnumber and numentries
        var setnumber = '';
        var numentries = '';
        store.each(function(record){
            setnumber = record.get('setnumber');
            numentries = record.get('numentries');
        });
        
        //reset the result range display to 1 - 10
        var getcurrentpagenum = '1';
        var nextpagenumber = '10';
        //set search condition (setnumber, page (1), sortby(sortkey), numberofrecordstoretrieve(10)) [split by U5R]
        var newset = setnumber + 'U5R1' + 'U5R' + sortkey + 'U5R10';
        
        //change the condition if the result have less then 10 records
        if(numentries < 10){
            //set search condition (setnumber, page (1), sortby(sortkey), numberofrecordstoretrieve(numentries)) [split by U5R]
            newset = setnumber + 'U5R1' + 'U5R' + sortkey + 'U5R' + numentries;
            nextpagenumber= numentries;
        }
        //sort and retrieve the results
        resultStore.load({
            callback: function(records, operation, success) {            
                //set currentstart to 1
                store.getAt(0).set('currentstart', getcurrentpagenum);
                //set currentend to nextpagenumber
                store.getAt(0).set('currentend', nextpagenumber);
                //set currentpagenumber to 1
                store.getAt(0).set('currentpagenumber', '1');
                //display the record range
                var displaytext = 'Result ' + getcurrentpagenum + ' - ' + nextpagenumber + ' of ' + numentries
                var resultRangeBtn = scope.getResultRangeButton();
                resultRangeBtn.setHtml(displaytext);
            },//callback
            url: MajorProjectSenchaTouch.app.serverUrl +'NewArrivals/retrieveSortList/' + newset
        });
    },
/*
|--------------------------------------------------------------------------
| pushView (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| Set the title of the navigation bar and push the page into the navigation
| view.
|
*/ 
    pushView: function(setTitle, setXtype){
        var view = this.getNavView();
        view.push({
            title: setTitle,
            xtype: setXtype
        })
    },
 /*
|--------------------------------------------------------------------------
| showMask (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| Get the current item in the navigation view and set the loading mask.
| Return the current item as previousPage.
|
*/  
    showMask: function(){
        var view = this.getNavView();
        var previousPage = view._activeItem;
        
        previousPage.setMasked({
            xtype: 'loadmask',
            message: 'Please wait...'
        });
        
        return previousPage;
    },
    
	setToDefault: function(){
        var selectField = this.getSelectedfield();
        selectField.setValue('New Books');
    },
	
    /*
|--------------------------------------------------------------------------
| hideMask (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| Hide the loading mask of the page.
|
*/  
    hideMask: function(previousPage){        
        previousPage.setMasked(false);
    }
});


